<script src="../../../../public/static/rong/src/assets/js/protobuf-2.1.3.min.js"></script>{extend name="public/base"}

{block name="title"}就行天下-消息{/block}

{block name="style"}
<link rel="stylesheet" href="__STATIC__/home/css/message.css" />
{/block}

{block name="main"}
<div class="pageControl inform">
    <div class="main-top"></div>
    <div class="msui_nav msui_navTop">
        <a class="msui_navTop-back" href="javascript:history.back();"><i class="micon-back"></i></a>
        <h1 class="msui_navTop-title">{$list.peer_nickname}</h1>
        <a href="" class="msui_navTop-right msui_navTop-cnav"><i class="micon-cnav"></i></a>
    </div>
    <div class="ms-main">
        {notempty name="list.list"}
        {volist name="list.list" id="vo"}
        <div class="{$vo.action == 'send' ? 'm_right' : 'm_left'}">
            <p><img src="{$vo.headimgurl}" alt=""/></p>
            <p class="{$vo.action == 'send' ? 'right-main' : 'left-main'}">{$vo.msg}</p>
            <i class="icon_san"></i>
        </div>
        {/volist}
        {/notempty}
    </div>
    <div id="mshua" style="bottom: 0;">
        <div class="weui-cell mshua">
            <div class="weui-label">
                <a href="1" class="ms-tab" id="ms-bq"><img src="__STATIC__/home/images/k3.png" alt="div"/></a>
            </div>
            <div class="weui-label">
                <a href="2" class="ms-tab" id="ms-jia"><img src="__STATIC__/home/images/k2.png" alt="div"/></a>
            </div>
            <div class="weui-cell__bd">
                <input type="text" id="ms_input" class="weui-input ms-input"/>
            </div>
            <div class="weui-cell__ft">
                <a href="" class="ms-btn ">发送</a>
            </div>
        </div>
        <div class="ms-tab-panel" style="display:none;">
            <div class="weui-flex " id="s2">
                <div class="ms-f">
                    <a href="" class="ms-flex"><img src="__STATIC__/home/images/k5.png" alt=""/></a>
                </div>
                <div class="ms-f">
                    <a href="" class="ms-flex"><img src="__STATIC__/home/images/k6.png" alt=""/></a>
                </div>
            </div>
            <div class="weui-flex active" id="s1">
                <div class="swiper-container1">
                    <div class="swiper-wrapper">
                        <div class="swiper-slide"> </div>
                    </div>
                    <div class="swiper-pagination"></div>
                </div>
            </div>
        </div>
    </div>
</div>
{/block}

{block name="javascript"}
<script src="__STATIC__/home/jquery_weui/js/swiper.min.js"></script>
<script src="__STATIC__/rong/dist/assets/js/RongIMLib.js"></script>
<script src="http://cdn.ronghub.com/RongEmoji-2.2.5.min.js"></script>
<script>
    $(function(){
        var mshuaTop = $(document).height();
        $('html, body').animate({
            scrollTop: mshuaTop
        }, 400);

        $('.ms-input').focus(function () {
            var mshuaTop=$("#mshua").offset().top;
            $('html, body').animate({
                scrollTop: mshuaTop
            }, 1000);
        });

        $("#s1").on("click","a",function (e) {
            e.preventDefault();
            var d = $(this).attr("title");
            ms_input.value+=d;

        });
        $(".ms-tab").click(function (e) {
            e.preventDefault();
//            var mshuaTop=$("#mshua").offset().top;

            $('html, body').animate({
                scrollTop: mshuaTop
            }, 1000);
            var d = $(this).attr("href");
            $(`#s${d}`).addClass('active').siblings().removeClass('active');
            $(".ms-tab-panel").show();
//            $("#mshua").css("bottom", "0");
            $(".ms-main>div:last-child").css("margin-bottom", "12rem");

        });
        $(".ms-main").click(function () {
//            $("#mshua").css("bottom", "-9rem");
            $(".ms-tab-panel").hide();
            $(".ms-main>div:last-child").css("margin-bottom", "4rem");
        });
//        发送消息
        $(".ms-btn").click(function (e) {
            var mshuaTop = $("#mshua").offset().top;
            console.log(mshuaTop);
            $('html, body').animate({
                scrollTop: mshuaTop
            }, 1000);
            e.preventDefault();
            var t = $(".ms-input").val();
            var html = "";
            if (t !== "") {
                t = RongIMLib.RongIMEmoji.symbolToEmoji(t);
                html = $(".ms-main").html() + `
                    <div class="m_right">
                        <p><img src="{$list.me_headimgurl}" alt=""/></p>
                        <p class="right-main">${t}</p>
                        <i class="icon_san"></i>
                    </div>
            `;
                $(".ms-main").html(html);
                $(".ms-main>div").css("margin-bottom", "0");
                if ($(".ms-tab-panel:visible")) {
                    $(".ms-main>div:last-child").css("margin-bottom", "12rem");
                } else {
                    $(".ms-main>div:last-child").css("margin-bottom", "4rem");
                }

                var msg = new RongIMLib.TextMessage({content:t,extra:"附加信息"});
                var conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可。
                var targetId = "{$data.targetId}"; // 目标 Id
                RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
                        onSuccess: function (message) {
                            //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                            console.log("Send successfully");
//                            alert("Send successfully");
                            console.log(targetId);
                            console.log(msg);
                            //console.log(message);

                            // 添加消息记录
                            var _content = RongIMLib.RongIMEmoji.symbolToEmoji(msg.content);
                            $.post('{:url("save_rong_msg")}',{ userId : '{$data.userId}', targetId : targetId, msg : _content }, function (msg) {
                                console.log(msg);
                            });
                        },
                        onError: function (errorCode,message) {
                            var info = '';
                            switch (errorCode) {
                                case RongIMLib.ErrorCode.TIMEOUT:
                                    info = '超时';
                                    break;
                                case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                                    info = '未知错误';
                                    break;
                                case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                                    info = '在黑名单中，无法向对方发送消息';
                                    break;
                                case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                                    info = '不在讨论组中';
                                    break;
                                case RongIMLib.ErrorCode.NOT_IN_GROUP:
                                    info = '不在群组中';
                                    break;
                                case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                                    info = '不在聊天室中';
                                    break;
                                default :
                                    info = x;
                                    break;
                            }
                            alert(info);
                            console.log('发送失败:' + info);
                        }
                    }
                );
                ms_input.value = '';
            }
        });


        /**
         * 开始融云业务逻辑
         * @type {{appKey, token, navi}}
         */
        var params = {
            appKey : '{$Think.config.rong.app_key}',
            token : '{$data.token}',
            navi : ''
        };

        var userId = "";

        var callbacks = {
            getInstance : function(instance){
                RongIMLib.RongIMEmoji.init();
                var emojis = RongIMLib.RongIMEmoji.emojis;
                emojis.forEach(function(value, index, array) {
                    var _this = $(value);
                    var emoji_html = '<a href="javascript:void(0);" title="' + _this.find('span').attr('name') + '">'+_this.find('span').html()+'</a>';
                    if ($(".swiper-slide").eq(-1).find('a').length >= 24 || $(".swiper-slide").length == 0) {
                        $(".swiper-wrapper").append('<div class="swiper-slide">'+ emoji_html +'</div>')
                    } else {
                        $(".swiper-slide").eq(-1).append(emoji_html);
                    }
                });
                var swiper = new Swiper('.swiper-container1', {
                    pagination: '.swiper-pagination',
                    slidesPerView: 1,

                    paginationClickable: true,
                    spaceBetween: 5,
                });
            },
            getCurrentUser : function(userInfo){
                console.log(userInfo.userId);
                userId = userInfo.userId;
//                alert("链接成功；userid=" + userInfo.userId);
            },
            receiveNewMessage : function(message){
                //判断是否有 @ 自己的消息
                var mentionedInfo = message.content.mentionedInfo || {};
                var ids = mentionedInfo.userIdList || [];
                for(var i=0; i < ids.length; i++){
                    if( ids[i] == userId){
                        alert("有人 @ 了你！");
                    }
                }
                var targetId = "{$data.targetId}"; // 目标 Id
                if (message.targetId == targetId) {
                    var content = message.content.content;

                    content = RongIMLib.RongIMEmoji.emojiToSymbol(content);
                    content = RongIMLib.RongIMEmoji.symbolToEmoji(content);

                    if (message.content.imageUri) {
                        content = '<img src="'+ message.content.imageUri +'" />';
                    }
                    if (message.content.messageName == 'SyncReadStatusMessage') {
                        content = '撤回一条消息';
                    }
                    var html = '';
                    html += '<div class="m_left">';
                    html += '   <p><img src="{$list.peer_headimgurl}" alt=""/></p>';
                    html += '   <p>'+ content +'</p>';
                    html += '   <i class="icon_san"></i>';
                    html += '</div>';
                    $('.ms-main').append(html);
                    $(".ms-main>div").css("margin-bottom", "0");
                    console.log($(".ms-tab-panel").is(":visible"));
                    if ($(".ms-tab-panel").is(":visible")) {
                        $(".ms-main>div:last-child").css("margin-bottom", "12rem");
                    } else {
                        $(".ms-main>div:last-child").css("margin-bottom", "4rem");
                    }
                    var mshuaTop=$("#mshua").offset().top;
                    console.log(mshuaTop);
                    $('html, body').animate({
                        scrollTop: mshuaTop
                    }, 1000);
                }
                console.log(message);
            }
        };

        rong_init(params,callbacks);

    });
</script>
{/block}